package com.locoboard;

import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.location.Location;
import android.widget.EditText;
import android.widget.LinearLayout;

/**
 * This class manages the retrieval and posting of messages 
 * within the application.
 * @author Gordon Meyer 02/13
 */
public class MessageManager {
	/************************************************
	 * 		Static Members
	 */
	private static final int MESS_GET_WAIT = 30 * 1000;	//30 seconds 
	
	private static Timer timer = null;	
	private static volatile boolean isGetingMes = false;
	private static volatile boolean isPostingMes = false;
	
	private static LinkedList<Post> messages = null;

	/************************************************
	 * 		Static Functions
	 */
	public static synchronized void setGettingMess(boolean b){
		isGetingMes = b;
	}
	
	public static synchronized boolean isGetingMessages(){
		return isGetingMes;
	}
	
	/**
	 * Will attempt to contact the server if the application
	 * is not currently getting messages.
	 */
	public static void getMessagesOnce(){
		Location last = PositionManager.getLocation();
    	if(last != null){    		
    		if(!isGetingMessages()){
    			setGettingMess(true);
    			new GetMessages().execute();    			
    		}
    	}    	
	}
	
	/**
	 * Calls getMessagesOnce on timer every
	 * MESS_GET_WAIT milliseconds.
	 */
	public static void getMessagesOnTimer(){
		getMessagesOnce();
		if(timer == null){
			timer = new Timer();
			timer.schedule(new TimerTask(){
				@Override
				public void run() {
					getMessagesOnce();					
				}				
			}, MESS_GET_WAIT);
		}
	}
	
	/**
	 *  Stops the get message timer
	 */
	public static void stopMessagesTimer(){
		if(timer != null){
			timer.cancel();
			timer.purge();
			timer = null;
		}
	}
	
	/**
	 *  Sends a message to the server from current location
	 * @param s The message to post.
	 * @return True if post successful.  False otherwise.
	 */
	public static boolean postMessage(String s){
		if(!isPostingMes && s != null && s.length() <= Globals.MAX_CHAR_PER_MES && s.length() > 0){
			isPostingMes = true;
			new PostMessage().execute(s);
			return true;
		}
		return false;
	}
	
	/**
	 * Makes a new list of messages the active list of messages.
	 * @param mess The new list of messages.
	 */
	public static void processMessages(LinkedList<Post> mess){
		if(messages != null){
			messages.clear();			
		}
		messages = mess;
	}
	
	/**
	 * Display the new messages
	 * Must be called from the UI thread.
	 */
	public static void displayNewMessages(){
		if(messages != null){
			LinearLayout ll = (LinearLayout)Globals.getMainActivity().findViewById(R.id.scrvMessBoard);
			// clear current message bubbles
			ll.removeAllViews();
			
			GoogleMap map = ((MapFragment)Globals.getMainActivity().getFragmentManager().findFragmentById(R.id.map)).getMap();
			
			for(Post p : messages){
				MessageBubble mb = new MessageBubble(Globals.getContext(), p.text);
				
				// add bubble
				ll.addView(mb);
				
				// add marker to map
				if(map != null){
					MarkerOptions options = new MarkerOptions();
					LatLng latlng = new LatLng(Double.valueOf(p.lat), Double.valueOf(p.lng));
					options.position(latlng);
					options.title(p.text);
					map.addMarker(options);
				}
			}
		}
	}
	
	/************************************************
	 * 		Event Handlers
	 */
	
	/**
	 * Called when background GetMessages task is complete
	 */
	public static void onGetComplete(){
		setGettingMess(false);
	}
	
	/**
	 * Called when the background PostMessage task is complete.
	 * Must be called from UI thread
	 * @param wasSuccessful True if message posted successfully.  False otherwise.
	 */
	public static void onPostComplete(boolean wasSuccessful){
		EditText txtBox = (EditText)Globals.getMainActivity().findViewById(R.id.edtxtMessage);
		
		if(wasSuccessful){
			txtBox.setText("");
		}		
		txtBox.setEnabled(true);
		
		//refresh messages
		stopMessagesTimer();
		getMessagesOnTimer();		
		
		isPostingMes = false;
	}
}
